package org.example.route.service.impl;

import com.aliyun.oss.OSS;
import org.example.route.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OSS ossClient;

    @Value("${oss.bucket-name}")
    private String bucketName;

    public String uploadFile(MultipartFile file) throws IOException {
        String fileName = generateFileName(file.getOriginalFilename());
        ossClient.putObject(bucketName, fileName, file.getInputStream());
        return ossClient.generatePresignedUrl(bucketName, fileName,
                Date.from(Instant.now().plus(365, ChronoUnit.DAYS))).toString();
    }

    private String generateFileName(String originalName) {
        String suffix = originalName.substring(originalName.lastIndexOf("."));
        return System.currentTimeMillis() + "_" +
                UUID.randomUUID().toString().replace("-", "") + suffix;
    }
}
